package MusicPlayer;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/MusicPlayer.getSongs") // 定义访问路径
public class SongServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 定义音乐文件夹的路径 (相对于服务器的根目录)
        String musicFolderPath = new File(getServletContext().getRealPath("/")) +"\\Music";
        // 保存歌曲列表
        List<String> songs = new ArrayList<>();

        // 读取音乐文件夹内容
        File musicFolder = new File(musicFolderPath);
        if (musicFolder.exists() && musicFolder.isDirectory()) {
            File[] files = musicFolder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".mp3")) {
                        songs.add(file.getName());
                    }
                }
            }
        }
        // 设置响应内容类型为 JSON，避免乱码
        response.setContentType("application/json; charset=UTF-8");
        // 将歌曲列表转换为 JSON 格式并写入响应
        Gson gson = new Gson();
        String json = gson.toJson(songs);
        response.getWriter().write(json);
        System.out.println(json);
    }
}
